package com.servlets;

import com.alibaba.fastjson.JSON;
import com.pojo.Product;
import com.pojo.ShopCart;
import com.pojo.ShopCartProduct;
import com.pojo.Users;
import com.service.ProductService;
import com.service.ShopCartProductService;
import com.service.impl.ProductServiceImpl;
import com.service.impl.ShopCartProductServiceImpl;
import com.service.impl.ShopCartServiceImpl;
import com.utils.JDBCUtil;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.UUID;

@WebServlet("/shopCartProduct.do")
public class ShopCartProductServlet extends BaseServlet{
    private ShopCartProductService service = new ShopCartProductServiceImpl();
    private ProductService ps = new ProductServiceImpl();

    public void findShopCart(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        response.setContentType("application/json;charset=utf-8");
        //1.获取用户ID
        String userID = request.getParameter("userID");
        //2.获取用户的购物车
        ShopCart shopCart = new ShopCartServiceImpl().findByUserID(userID);
        //3.根据购物车ID查询商品ID;
        List<ShopCartProduct> shopCartProducts = service.findByShopCartID(shopCart.getCartId());
        List<Product> list = new ArrayList<>();
        if (shopCartProducts.size()>0){
            for (ShopCartProduct shopCartProduct : shopCartProducts) {
                Product product = ps.findByID(shopCartProduct.getProductId());
                product.setProductNum(shopCartProduct.getProductNum());
                list.add(product);
            }
        }
        response.getWriter().write(JSON.toJSONString(list));
    }

    public void add(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException{
        response.setContentType("application/json;charset=utf-8");
        //1.获取用户ID
        String userID = request.getParameter("userID"),msg;
        //2.获取用户的购物车
        ShopCart shopCart = new ShopCartServiceImpl().findByUserID(userID);
        //3.将post提交的参数封装到类
        Map<String, String[]> map = request.getParameterMap();
        ShopCartProduct shopCartProduct = JDBCUtil.mapToBean(map, ShopCartProduct.class);
        shopCartProduct.setId(UUID.randomUUID().toString().replace("-","").substring(0,10));
        //4.将购物车id赋值给购物车商品类
        shopCartProduct.setShopCartId(shopCart.getCartId());
        //5.添加数据
        if(service.addSCP(shopCartProduct))
            msg = "添加成功";
        else
            msg = "添加失败";
        response.getWriter().write(JSON.toJSONString(msg));

    }
}
